import superModule from "./superModule";
import o1MessageBox from "./uiModule/o1MessageBox";
import o1DialogBox from "./uiModule/o1DialogBox";
import o1Loading from "./uiModule/o1Loading";
import O1HD from "../gameEngine";
import RewardView from "../../O1ModuleRes/control/RewardView";
import { REWARD_TYPE } from "../services/userContent/userInterface";
import addUserProp from "../../O1ModuleRes/control/addUserProp";
import mainRoot from "../../Game/MainRoot";
import data_control from "../libs/data_control";
import gameConfig from "../configs/gameConfig";
import { PAGE } from "../../Game/Enum";
import AddDestokPage from "../../Game/Page/AddDestokPage";
import loadingAni from "../../O1ModuleRes/control/loadingAni";

export enum UI_Z_INDEX {
    NORMAL,
    DIALOG = 10,
    MESSAGE,
    LOADING
}

export default class uiModule extends superModule {

    protected m_className: string = 'UI模块';

    //
    private readonly m_pathFrameBundle: string = 'o1ModuleRes';
    //
    private readonly m_pathGameBundle: string = 'gameBundle';
    //
    private readonly m_pathPreloadFrame: string = 'preload/frame';
    //
    private readonly m_pathPreloadGame: string = 'preload';

    private readonly InfinityModel: string = 'user-is-infinity';
    private readonly InfinityPower_Key: string = 'user-logintime';

    //全局框架bundle
    private m_frameBundle: cc.AssetManager.Bundle = null;
    //游戏公用bundle
    private m_gameBundle: cc.AssetManager.Bundle = null;

    constructor() {
        super();
    }

    //高斯模糊
    private m_uiBgTexture: cc.RenderTexture = null;
    private m_uiBgSpriteFrame = null;

    //设置高模
    setGaussianMode(bgNode: cc.Node) {
        return;
        //暂时不需要
        // //
        // if (!bgNode.isValid) return;
        // //
        // this.changeCurrCanvasPicture();
        // //高斯模糊
        // if (bgNode) {
        //     bgNode.getComponent(cc.Sprite).spriteFrame = this.m_uiBgSpriteFrame;
        // }
        // // }, 0.01666);
    }

    // private changeCurrCanvasPicture() {
    //     if (this.m_uiBgTexture) {
    //         delete this.m_uiBgTexture;
    //     }
    //     if (this.m_uiBgSpriteFrame) {
    //         delete this.m_uiBgSpriteFrame;
    //     }
    //     //
    //     this.m_uiBgTexture = new cc.RenderTexture();
    //     this.m_uiBgTexture.initWithElement(cc.game.canvas);
    //     this.m_uiBgSpriteFrame = new cc.SpriteFrame(this.m_uiBgTexture);
    // }

    //预加载框架资源路径
    getFrameBundlePreloadResPath(): string {
        return this.m_pathPreloadFrame;
    }

    //预加载游戏资源路径
    getGameBundlePreloadResPath(): string {
        return this.m_pathPreloadGame;
    }

    async preLoadModules(): Promise<void> {
        return super.preLoadModules();
    }

    async loadModule(): Promise<void> {
        return super.loadModule();
    }

    /**
     * 显示消息
     * @param message 消息文本
     * @param parentNode 父节点
     * @param 显示时间
     * */
    showMessageBox(message: string, parentNode: cc.Node = null, showTime: number = 2) {
        parentNode = parentNode || mainRoot.UIRoot;
        this.m_frameBundle.load(`${this.m_pathPreloadFrame}/o1MessageBox`, cc.Prefab, (error, assets: cc.Prefab) => {
            if (error) {
                console.error('#40错误 错误消息框预制体', error);
                return;
            }
            //
            let node = cc.instantiate(assets);
            node.getComponent(o1MessageBox).showMessageBox(message, showTime);
            parentNode.addChild(node, UI_Z_INDEX.MESSAGE);
        })
    }

    
    /**添加桌面 */
     addShortcutBox( parentNode: cc.Node = null) {
          //字节跳动 字节跳动lite 和西瓜拒审 关闭

        if(!mainRoot.isShortcutOpen()) {
            return
        }
      
        parentNode = parentNode || mainRoot.UIRoot;
        this.m_frameBundle.load(`${this.m_pathPreloadFrame}/addDestokPage`, cc.Prefab, (error, assets: cc.Prefab) => {
            if (error) {
                console.error('#40错误 错误消息框预制体', error);
                return;
            }
            //
            let node = cc.instantiate(assets);
            parentNode.addChild(node, UI_Z_INDEX.MESSAGE);
        })
    }


    private isOKRightOrUnderlie: boolean = true;
    // CP -按钮交换位置模式   DS -取消按钮延迟显示模式   CC -默认勾选看视频领奖励模式
    private readonly dlgBoxName_VD: string[] = ["o1DialogBox_VD_CP", "o1DialogBox_VD_DS", "o1DialogBox_VD_CC"];

    /**
     * 显示模态对话框 看视频按钮请注意文本长度 要 与取消文本所在按钮同大小
     * @param title 标题
     * @param message 文本
     * @param isCancelOk 是否有取消按钮
     * @param clickCallBack 点击回调 是否确定
     * @param parentNode 父节点
     * @param okButtonText 确定按钮自定义文本
     * @param cancelButtonText 取消按钮自定义文本
     * @param lookVideoCount 观看视频次数
     * @param ovVideoAdPatternIndex ov平台激励视频弹窗样式选择，无输入则随机： 0 -CP  1 -DS  2 -CC
     * @param lookVideoSource 观看视频目的
     * */
    showDialogBox(title: string, message: string,
        isCancelOk: boolean = false,
        clickCallBack?: (isOk: boolean) => void,
        parentNode: cc.Node = null,
        okButtonText?: string,
        cancelButtonText?: string,
        lookVideoCount?: number,
        ovVideoAdPatternIndex: number = null,
        lookVideoSource?: string) {
        parentNode = parentNode || mainRoot.UIRoot;
        //
        //
        this.m_frameBundle.load(`${this.m_pathPreloadFrame}/o1DialogBox`, cc.Prefab, (error, assets: cc.Prefab) => {
            if (error) {
                console.error('#40错误 错误对话框预制体', error);
                return;
            }
            let node = cc.instantiate(assets);
            node.getComponent(o1DialogBox).showDialogBox(title, message, isCancelOk, clickCallBack, okButtonText, cancelButtonText, lookVideoCount, lookVideoSource);
            parentNode.addChild(node, UI_Z_INDEX.DIALOG);
        })

    }

    private m_loadingNode: cc.Node = null;
    private m_loadingOver: boolean = false;

    /**
     * 显示加载
     * @param parentNode 父节点
     * @param loadingText 加载文本
     * */
    async showLoading(parentNode: cc.Node = null, loadingText: string = '正在加载') {
        return new Promise<void>(resolve => {
            this.m_loadingOver = false;
            parentNode = parentNode || mainRoot.UIRoot;
            this.m_frameBundle.load(`${this.m_pathPreloadFrame}/o1Loading`, cc.Prefab, async (error, assets: cc.Prefab) => {
                if (error) {
                    console.error('#40错误 错误对话框加载', error);
                    return resolve();
                }
                // if (this.m_loadingOver) {
                //     this.hideLoading();
                //     return resolve();
                // }
                if (this.m_loadingNode) {
                    if (this.m_loadingNode.isValid) {
                        this.m_loadingNode.removeFromParent(false);
                    } else {
                        this.m_loadingNode.destroy();
                        this.m_loadingNode = null;
                    }
                }
                if (!this.m_loadingNode) {
                    this.m_loadingNode = cc.instantiate(assets);
                }
                this.m_loadingNode.getComponent(o1Loading).showLoading(loadingText)
                parentNode.addChild(this.m_loadingNode, UI_Z_INDEX.LOADING);
                this.m_loadingNode.setPosition(0, 0);
                // await this.m_loadingNode.getChildByName("loading").getComponent(loadingAni).fontAni();
                console.log("重新加载loading也", this.m_loadingNode.x, this.m_loadingNode.y);
                resolve();
            })
        });
    }

    /**
     * 展示无限体力界面
     * @param showProbability 展示无限体力的概率 1为必现  已经有无限体力不会展示
     * @param parentNode 父节点
     */
    showInfinityPower(showProbability: number, parentNode: cc.Node) {
        let that = this
        if(window['tt']){
            window['tt'].checkShortcut({
                success: function (res) {
                    console.info("success快捷方式 showInfinityPower",res)
                    if(res.status.exist){
                        console.info("success快捷方式存在")
                    }else{
                        console.info("success快捷方式不存在")
    
                        that.addShortcutBox()
                    }
                    //获取快捷方式是否存在 res.status.exist
                },
                fail: function (res) {
                    console.info("fail快捷方式检查showInfinityPower",  res.errMsg)
                }
            })
        }
        
        let dateOld = O1HD.getServices().localStorageSrv.getStorage(this.InfinityPower_Key)
        if (dateOld) {
            let rand = Math.random();
            if (Number(O1HD.getServices().localStorageSrv.getStorage(this.InfinityModel)) == 0) {
                if (rand < showProbability) {
                    this.createAndShowInfinityPower(parentNode);
                }
            } else {
                this.showMessageBox(`无限畅玩 ${data_control.MinusToHours(gameConfig.INFINITY_POWER_VIDEO_HAND_TIME)} 已解锁`);
            }
        } else {
            //todo 第一次登陆
            O1HD.getServices().localStorageSrv.setStorage(this.InfinityPower_Key, Date.now());
            this.createAndShowInfinityPower(parentNode);
        }
    }
//电子邮件puhalskijsemen@gmail.com
//源码网站 开vpn全局模式打开 http://web3incubators.com/
//电报https://t.me/gamecode999

    /**
     * 获取金币体力钻石等
     * @param rewardType 奖励类型
     * @param rewardCount 数量
     * @param parentNode 父节点
     */
    showUserPropGet(rewardType: REWARD_TYPE, rewardCount: number, parentNode?: cc.Node, overCb?: () => void) {
        let that = this
        if(window['tt']){
            window['tt'].checkShortcut({
                success: function (res) {
                    console.info("success快捷方式 showUserPropGet",res)
                    if(res.status.exist){
                        console.info("success快捷方式存在")
                    }else{
                        console.info("success快捷方式不存在")
    
                        that.addShortcutBox()
                    }
                    //获取快捷方式是否存在 res.status.exist
                },
                fail: function (res) {
                
                    console.info("fail快捷方式检查showUserPropGet",  res.errMsg)
                
                }
            })
        }

        this.showFramePrefab('preload/control/addUserProp', parentNode, true, node => {
            node.getComponent(addUserProp).setData(rewardType, rewardCount);
            overCb && overCb();
        });
    }

    /***
     * 显示获得的奖励
     * @param rewardType 奖励类型
     * @param rewardCount 奖励数量
     * @param titleString 奖励标题
     * @param customSpriteFrame 奖励图片
     * @param parentNode 父节点
     * @constructor
     */
    showGetRewarded(rewardType: REWARD_TYPE, rewardCount: number, titleString?: string, customSpriteFrame?: cc.SpriteFrame, parentNode?: cc.Node) {
        parentNode = parentNode || mainRoot.UIRoot;
        this.showFramePrefab('preload/control/RewardView', parentNode, true, node => {
            node.getComponent(RewardView).OnShowReward(rewardType, rewardCount, titleString, customSpriteFrame);
        })
    }

    /**
     * 展示无限体力界面
     * @param parentNode 父节点
     */
    private createAndShowInfinityPower(parentNode: cc.Node) {
        parentNode = parentNode || mainRoot.UIRoot;
        this.showFramePrefab('preload/infinitypower', parentNode, false, node => {

        })
        // this.m_frameBundle.load('preload/infinitypower', cc.Prefab, (error, assets: cc.Prefab) => {
        //     if (error) {
        //         console.error("无限体力预制体加载失败", error);
        //         return;
        //     }
        //     let InfinityPower = cc.instantiate(assets);
        //     InfinityPower.scale = 0.1;
        //     parentNode.addChild(InfinityPower);//展示无限体力页面
        //     cc.tween(InfinityPower).to(0.3, {scale: 1}, {easing: "backOut"}).start();
        // });
    }

    /**
     * 隐藏加载
     * */
    hideLoading() {
        console.log("#关闭loading异常");
        this.m_loadingNode && this.m_loadingNode.isValid && this.m_loadingNode.destroy();
        this.m_loadingNode = null;
        this.m_loadingOver = true;
    }

    getFrameBundlePath() {
        return this.m_pathFrameBundle;
    }

    getGameBundlePath() {
        return this.m_pathGameBundle;
    }

    setFrameBundle(bundle: cc.AssetManager.Bundle) {
        this.m_frameBundle = bundle;
    }

    setGameBundle(bundle: cc.AssetManager.Bundle) {
        this.m_gameBundle = bundle;
    }

    getFrameBundle() {
        return this.m_frameBundle;
    }

    getGameBundle() {
        return this.m_gameBundle;
    }

    /**
     * 显示预制体
     * @param inPrefabPath 预制体在子包的路径
     * @param parentNode 父节点
     * @param isShowLoading 显示/不显示 加载条
     * @param addedCallback 成功回调
     */
    showFramePrefab(inPrefabPath: string, parentNode?: cc.Node, isShowLoading?: boolean, addedCallback?: (node: cc.Node) => void) {
        //c
        parentNode = parentNode || mainRoot.UIRoot;
        //
        if (isShowLoading) {
            this.showLoading();
        }
        this.m_frameBundle.load(inPrefabPath, cc.Prefab, (error, assets: cc.Prefab) => {
            if (isShowLoading) {
                
                this.hideLoading();
            }
            if (error) {
                console.error('#446 错误 ui加载预制体', inPrefabPath);
                return;
            }
            //
            if (parentNode && parentNode.isValid) {
                let node = cc.instantiate(assets);
                parentNode.addChild(node);
                addedCallback && addedCallback(node);
            } else {
                console.error('#453 错误 ui 父节点已失效', inPrefabPath, Date.now());
            }
        })
    }

    /**
     * 显示隐藏对话框动画
     * @param node 目标节点
     * @param isShow 显示为真 隐藏为假
     * @param cb 动画完成回调
     */
    showHideDialogAnimation(node: cc.Node, isShow: boolean, cb?: () => void) {
        //
        if (node && node.isValid) {
            const SCALE_TIME = 0.26;
            if (isShow) {
                node.scale = 0;
                cc.tween(node)
                    .parallel(
                        cc.tween(node).to(SCALE_TIME, { scale: 1 }),
                        cc.tween(node)
                            .by(SCALE_TIME * 0.45, { y: 250 }, { easing: 'cubicOut' })
                            .by(SCALE_TIME * 0.55, { y: -250 }, { easing: 'cubicIn' })
                    )
                    .call(cb)
                    .start();
            } else {
                cc.tween(node)
                    .parallel(
                        cc.tween(node).to(SCALE_TIME, { scale: 0 }),
                        cc.tween(node)
                            .by(SCALE_TIME * 0.55, { y: 250 }, { easing: 'cubicOut' })
                            .by(SCALE_TIME * 0.45, { y: -250 }, { easing: 'cubicIn' })
                    )
                    .call(cb)
                    .start();
            }
        }
    }
}




























